package com.shanjiduo.newsline.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.shanjiduo.newsline.LoginActivity;
import com.shanjiduo.newsline.R;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ContentFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ContentFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static String SCOPE = "all";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ListView list;
    private String[] names = {"搜索", "设置", "消息", "离线", "精彩应用", "反馈"};
    private int[] images = {R.drawable.ic_drawer_search_normal, R.drawable.ic_drawer_setting_normal
            , R.drawable.ic_drawer_message_normal, R.drawable.ic_drawer_offline_normal, R.drawable.ic_drawer_appstore_normal
            , R.drawable.ic_drawer_feedback_normal};
    private LinearLayout success;
    private LinearLayout none;
    private ImageView qqimg;
    private ImageView qqimage;
    private TextView qqname;
    private Tencent mTencent;
    private String App_ID = "1105924500";
    private IUiListener loginListener;
    private IUiListener userInfoListener;
    private IUiListener shareInfoListener;
    public ContentFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ContentFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ContentFragment newInstance(String param1, String param2) {
        ContentFragment fragment = new ContentFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_content, null);
        initQqLogin();
        list = (ListView) view.findViewById(R.id.menu_list);
        success = (LinearLayout) view.findViewById(R.id.login_qq);
        none = (LinearLayout) view.findViewById(R.id.login_none);
        qqimage = (ImageView) view.findViewById(R.id.qq_image);
        qqname = (TextView) view.findViewById(R.id.qq_name);
        qqimg = (ImageView) view.findViewById(R.id.qzone_btn);

        qqimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTencent.login(getActivity(), SCOPE, loginListener);
                none.setVisibility(View.GONE);
                success.setVisibility(View.VISIBLE);
            }
        });

        list.setAdapter(new MyAdapter());

        return view;
    }

 /*   @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
    }*/

    //初始化QQ登录分享的需要的资源
    private void initQqLogin() {
        try {
            mTencent = Tencent.createInstance(App_ID, getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //创建QQ登录回调接口
        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                //登录成功后回调该方法
                Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                //设置openid，如果不设置这一步的话无法获取用户信息
                JSONObject jo = (JSONObject) o;
                String openID;
                try {
                    openID = jo.getString("openid");
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(UiError uiError) {
                //登录失败后回调该方法
                Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                //取消登录后回调该方法
                Toast.makeText(getActivity(), "取消登录", Toast.LENGTH_SHORT).show();
            }
        };
        //获取用户信息的回调接口
        userInfoListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                JSONObject jo = (JSONObject) o;
                try {
                    JSONObject info = (JSONObject) o;
                    //获取用户具体信息
                    String nickName = info.getString("nickname");
                    String figureurl_qq_2 = info.getString("figureurl_qq_2");
                    new BitmapUtils(getActivity()).display(qqimage, figureurl_qq_2);
                    qqname.setText(nickName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        };
    }

    //获取用户信息
    private void getUserInfo() {
        UserInfo info = new UserInfo(getActivity(), mTencent.getQQToken());
        info.getUserInfo(userInfoListener);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // super.onActivityResult(requestCode, resultCode, data);
        //判断登陆成功

        //QQ登陆回调
        // Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        //一定要加上，不然监听不起作用
        Tencent.handleResultData(data, loginListener);
        //获取用户信息
        Log.d("onActivityResult", "成功执行了——————————————————————");
        getUserInfo();

    }

    //QQ登陆回调

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return images.length;
        }

        @Override
        public String getItem(int i) {
            return names[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = View.inflate(getActivity(), R.layout.menu_list_layout, null);
            ImageView img = (ImageView) view.findViewById(R.id.menu_list_image);
            TextView name = (TextView) view.findViewById(R.id.menu_list_name);
            img.setImageResource(images[i]);
            name.setText(names[i]);
            return view;
        }
    }
}
